<?php
/**
 * Created by allen.qiang. FUN-AC-0035-苏州1元拿破仑mini
 * User: Administrator
 * Date: 2015-03-04
 * Time: 下午16:50
 */
quanli_require('module/base/activity/activityConfig.class.php');

class activityWapMini {

    /**
     * 添加带来源标记的会员信息
     * @author  2015-03-04 allen.qiang <allen.qiang@fistforward.com>
     */
    public function quickLogin() {
        global $G_SHOP;

        //检查短信验证码
        $sms_ysm = $G_SHOP->sessionCache_get('sms_yzm_' . $_REQUEST['regName']);

        if (is_null($sms_ysm)) {
            returnJsonData('短信验证码已失效', 400);
        } elseif ($sms_ysm != md5($_REQUEST['smsyzm'])) {
            returnJsonData('短信验证码有误');
        }

        $G_SHOP->sessionCache_remove( 'sms_yzm_' . $_REQUEST['regName'] );
        $G_SHOP->sessionCache_remove( 'sms_yzm__time_' . $_REQUEST['regName'] );

        /**
         * =============================
         * 前台注册会员信息
         * =============================
         */

        //实例会员类
        quanli_require('module/base/customer/quanliCust.class.php');
        $quanliCust = new quanliCust();

        $pwd = get_random_string(6);

        //前台注册会员信息
        $args_array = array(
            'custID' => $_REQUEST['regName'],
            'pwd' => $pwd,
            'pwd2' => $pwd,
            'custSource' => $_REQUEST['custSource'],
            'custType' => 2,
            'custSource_ext' => $_REQUEST['cust_source_mark']  //会员来源扩展

        );
        $result_array = $this->registerAdd( $args_array );
        if ($result_array['code'] != 200) {
            returnJsonData($result_array['message'], $result_array['code']);
        }
        /**
         * =============================
         * 前台注册会员信息
         * =============================
         */

        //发送信息
        //加载短信类
        quanli_include('module/base/common/quanliSms.class.php');
        //实例化短信类
        $quanliSms = new quanliSms();

        $sms_content = "你好,欢迎加入xxxxx,您的用户名:".$args_array['custID'].",初始密码:".$args_array['pwd'].",请及时更改并保管好密码.";
        //发送短信
        $quanliSms->sendSMS( $args_array['custID'], $sms_content );


        /**
         * =============================
         * 更新会员登录信息
         * =============================
         */
        $quanliCust->shopCheckin( $result_array['data'] );
        /**
         * =============================
         * 更新会员登录信息
         * =============================
         */


        /**
         * ==========================
         * 渠道会员
         * ==========================
         */
        $tracker_code = $G_SHOP->get_cookie_info('__etrack_tracker_code');
        $key1 = $G_SHOP->get_cookie_info('__etrack_key1');
        $key2 = $G_SHOP->get_cookie_info('__etrack_key2');
        $key3 = $G_SHOP->get_cookie_info('__etrack_key3');
        $referrer = $G_SHOP->get_cookie_info('__etrack_referrer');
        $referrer_time = $G_SHOP->get_cookie_info('__etrack_referrer_time');
        $tracker = $G_SHOP->get_cookie_info('__etrack');
        $tracker_array = explode('|', $tracker);
        $etrack_switch = $G_SHOP->get_cookie_info('__etrack_switch');

        $cityName = '';
        $city_id = $G_SHOP->get_cookie_info('EBSIG_CITY_ID');

        if($city_id !== null){
            //获取城市名称
            $citySql = 'SELECT name FROM sys_region WHERE id = ' . intval($city_id);
            $cityRow = $G_SHOP->DBCA->stmt_query($citySql);
            $cityName = !empty($cityRow)?$cityRow[0]->name:'';
        }

        $cust_channel = new entity('cust_channel');
        $cust_channel->pcustID = $result_array['data']['pcustID'];
        if (!$G_SHOP->DBCA->fetch($cust_channel)) {
            $cust_channel->creator = 'system';
            $cust_channel->source_url = $referrer;
            $cust_channel->source_time = $referrer_time;
            $cust_channel->key1 = $key1;
            $cust_channel->key2 = $key2;
            $cust_channel->key3 = $key3;
            $cust_channel->tracker_code = $tracker_code;
            $cust_channel->session_id = $tracker_array[0];
            $cust_channel->switch_id = $etrack_switch;
            $cust_channel->ip = get_ip();
            $cust_channel->source_channel = $_REQUEST['custSource'] == 1 ? 'web' : 'wap';
            $cust_channel->city_name = $cityName;
            $G_SHOP->DBCA->save( $cust_channel );
        }
        /**
         * ==========================
         * 渠道会员
         * ==========================
         */


        returnJsonData('ok', 200, $result_array['data']['custID']);
    }

    /**
     * 注册会员
     * @param $arg_array
     * @return array
     */
    public function registerAdd( $arg_array ) {

        global $G_SHOP;

        //加载类文件
        quanli_include('module/base/customer/custRank.class.php');

        //实例会员等级类
        $custRank = new custRank();

        //检查参数
        if (!isset($arg_array['custID'], $arg_array['pwd'], $arg_array['custType'], $arg_array['custSource'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!in_array($arg_array['custType'], array(1, 2, 3))) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (!in_array($arg_array['custSource'], array(1, 2, 3, 4, 5, 6, 7))) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if ($arg_array['custSource'] != 7) {
            if (!is_mobile($arg_array['custID'])) {
                return array( 'code' => 400, 'message' => '请输入手机号码' );
            }
        }

        if (!is_pwd($arg_array['pwd'])) {
            return array( 'code' => 400, 'message' => '密码必须是6-30位字符，可使用字母、数字' );
        }

        if ($arg_array['custSource'] == 7) {
            $custID = $arg_array['custID'];
            $mobile = '';
        } else {
            $custID = $mobile = $arg_array['custID'];
        }

        $pwd = $arg_array['pwd'];

        //第三方登录会员名
        $unionName = isset($arg_array['unionName']) ? trim($arg_array['unionName']) : null;

        //会员昵称
        $nickName = isset($arg_array['nickName']) ? trim($arg_array['nickName']) : $custID;

        //推荐人客户号
        $recom_pcustID = isset($arg_array['referrer']) && is_numeric($arg_array['referrer']) ? $arg_array['referrer'] : null;

        //会员类型
        $custType = $arg_array['custType'];

        //会员来源
        $custSource = $arg_array['custSource'];

        //会员来源扩展
        $custSource_ext=$arg_array["custSource_ext"];

        try {

            //查询初始会员等级
            $rank_array = $custRank->getRankForNeedAmt( 0 );
            if (!$rank_array) {
                throw new Exception('会员数据未初始化', 404);
            }

            //检查会员并保存
            $cust_obj = new entity('cust_master');
            $cust_obj->custID = $custID;
            if ($G_SHOP->DBCA->fetch($cust_obj)) {
                throw new Exception('会员名已被使用，请使用其他会员名尝试注册', 404);
            }
            $cust_obj->creator = $custID;
            $cust_obj->pcustID = generate_seqno('seqno_customer');
            $cust_obj->nickName = $custID;
            $cust_obj->rankID = $rank_array['rankID'];
            $cust_obj->rankName = $rank_array['rankName'];
            $cust_obj->pwd = md5($pwd);
            $cust_obj->useFlg = 1;
            $cust_obj->head_pic = 'default_user.gif';
            $cust_obj->unionName = $unionName;
            $cust_obj->nickName = $nickName;
            $cust_obj->mobile = encryptD($mobile);
            $cust_obj->recom_pcustID = $recom_pcustID;
            $cust_obj->sumAmt = 0;
            $cust_obj->custSource = $custSource;
            $cust_obj->custType = $custType;
            $cust_obj->custSource_ext =$custSource_ext ;
            if (!$G_SHOP->DBCA->save($cust_obj)) {
                throw new Exception('页面已过期，请刷新页面重试', 404);
            }

            /**
             * =============================
             * 检查会员促销活动
             * =============================
             */

            //加载会员促销类
            quanli_include('module/base/promotion/promotionCustomer.class.php');


            //实例会员促销类
            $promotionHandler = new promotionCustomer();


            //查询会员促销活动并发放
            $promotionHandler->grantCustPromotion( $cust_obj->pcustID, $custID, 1 );


            /**
             * =============================
             * 检查会员促销活动
             * =============================
             */

            $result_array = array(
                'pcustID' => $cust_obj->pcustID,
                'custID' => $custID,
                'nickName' => $nickName,
                'email' => null,
                'custType' => $custType,
                'mobile' => $mobile,
                'recom_pcustID' => $recom_pcustID
            );

            return array( 'code' => 200, 'message' => 'ok', 'data' => $result_array );

        } catch (Exception $e) {

            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 判断会员是否有购买“wap端9.9元拿破仑mini”的权限
     * @$arg_array 参数对象
     * @return $result_array
     * @author  2015-03-05 allen.qiang <allen.qiang@fistforward.com>
     */
    public function isCompetence(&$arg_array,$config_code){
        global $G_SHOP;

        $result_array = array(
            'code' => 200,
            'message' => 'ok'
        );

        //实例化配置类
        $activity_config = new activityConfig($config_code);
        $config_array = $activity_config->config;
        //sql字符串
        $sql = ' ';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //会员名
        if (isset($arg_array['custID']) && is_numeric($arg_array['custID'])) {
            $sql .= ' AND custID = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['custID']);
        }

        //会员ID
        if (isset($arg_array['pcustID']) && !empty($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['pcustID'];
        }
        //判断是否是"wap端9.9元拿破仑mini"活动页注册的会员----start
        $sql_cust_master="SELECT createTime FROM cust_master WHERE custSource_ext='".$config_array["cust_source_mark"]."' ".$sql;
        $temp_item_cust_master = &$G_SHOP->DBCA->stmt_query($sql_cust_master,$params_type,$params_array);
        if($temp_item_cust_master){
            //判断会员是否已购买过“wap端9.9元拿破仑mini”---start
            $params_type .= 's';
            $params_array[] = $config_array['sku'];
            $sql_bill_master="SELECT COUNT(1) AS item_count FROM bill_master WHERE billPromotion =".$config_array["billPromotion"]. $sql ." AND bill_status<>10 AND bill_no IN (SELECT bill_no FROM bill_goods WHERE bill_no = bill_master.bill_no AND product_code = ? )";
            $temp_item_bill_master = &$G_SHOP->DBCA->stmt_query($sql_bill_master,$params_type,$params_array);
            if($temp_item_bill_master){
                $item_count2 = $temp_item_bill_master[0]->item_count;
                if ($item_count2> 0) { //会员已购买过“wap端9.9元拿破仑mini”
                    $result_array['code'] = 402;
                    $result_array['message'] = '您已购买过本次拿破仑mini蛋糕';
                }
            }
            //判断会员是否已购买过“wap端9.9元拿破仑mini”---end
        }else{ //未注册会员
            $result_array['code'] = 403;
            $result_array['message'] = '该会员不是活动页新注册的会员，无法参加本次活动';
        }

        //判断是否是"wap端9.9元拿破仑mini"活动页注册的会员----end
        return $result_array;
    }


    //提交wap端拿破仑mini订单
    public function create_bill( $bill ,$config_array) {

        global $G_SHOP;
        $goods_array[] = array(
            'sku' => $config_array["sku"],
            'num' => 1
        );
        if($config_array["config_code"]=="activity_wap_qcsmini"){
            $bill['deliver_provinceid'] = 664; //省
            $bill['deliver_cityid'] = 665;  //市
        }elseif(!isset($bill['deliver_provinceid']) && !isset($bill['deliver_cityid'])){
            $bill['deliver_provinceid'] = 10; //省
            $bill['deliver_cityid'] = 110;  //市
        }

        $bill['invoice_type'] = 1; //发票类型： 1、商业零售发票
        $bill['invoice_content'] = null;//发票内容
       // $bill['invoice_amount'] = 9.9; //发票金额
        $bill['invoice_number'] = null;//发票号
        $bill['is_urgent'] = 3;
        $bill['remark'] = '';
        $bill['billChannel'] = 2;
        $bill['billType'] = 1;
        $bill['external_bill_no'] = null;

        quanli_require('module/base/customer/quanliCust.class.php');
        quanli_require('module/base/customer/custDeliver.class.php');
        quanli_require('module/base/customer/custInvoice.class.php');
        quanli_require('module/base/system/sysRegion.class.php');
        quanli_require('module/base/system/sysDistribution.class.php');
        quanli_require('module/base/system/sysDistributionTechnician.class.php');
        quanli_require('module/base/system/sysPayment.class.php');
        quanli_require('module/base/bill/billCheckout.class.php');
        quanli_require('module/base/bill/billSearch.class.php');
        quanli_require('module/base/system/sysSend.class.php');
        quanli_require('module/base/goods/quanliGoods.class.php');
        quanli_require('module/base/goods/goodsFittings.class.php');
        quanli_require('module/base/promotion/quanliCoupon.class.php');
        quanli_require('module/base/promotion/quanliCard.class.php');

        $quanliGoods = new quanliGoods( $G_SHOP->DBCA );

        $quanliCust = new quanliCust();
        $custDeliver = new custDeliver();
        $custInvoice = new custInvoice();
        $sysDistribution = new sysDistribution();
        $sysPayment = new sysPayment();
        $billCheckout = new billCheckout();
        $sysSend = new sysSend();
        $sysRegion = new sysRegion( $G_SHOP->DBCA );

        /**
         * ==============================
         * 查询会员信息（如不存在则新建）
         * ==============================
         */
        $args_array = array(
            'custID' => $bill['custID']
        );
        $customer_array = $quanliCust->searchCustomerDetail( $args_array );
        if (!$customer_array) {
            return array('code'=>404,'message'=>'会员信息不存在,请先注册');
        }

        if($config_array["config_code"]=="activity_wap_miniBD"){
            $comp_result = $this->isCompetenceBD($args_array,$config_array["config_code"]);
        }else{
            $comp_result = $this->isCompetence($args_array,$config_array["config_code"]);
        }

        if($comp_result['code'] != 200)
        {
            return $comp_result;
        }

        //>>>>>>>>>>>>>>>>>//单量控制>>>>>>>>>>>>>>>>>>>
        $send_date_array = explode(',',$config_array['send_date_array']);
        $send_date_array_sw = explode(',',$config_array['send_date_array_sw']);
        $send_date_bill_limit_array = explode(',',$config_array['send_date_bill_limit_array']);

        $send_date_array_sql = array();
        foreach($send_date_array as $date_item)
        {
            $send_date_array_sql[] = "'$date_item'";
        }

        $sql_string = "SELECT bill_master.send_date,COUNT(1) AS bill_sum FROM bill_master
                    INNER JOIN bill_goods ON bill_master.bill_no = bill_goods.bill_no
                    WHERE bill_master.billPromotion = ".$config_array['billPromotion']."
                    AND bill_status<>10
                    AND bill_goods.product_code = '".$config_array['sku']."'
                    AND bill_master.send_date IN (". implode(',',$send_date_array_sql) .")
                    GROUP BY bill_master.send_date
                    ";

        $bill_array_sum = array();

        $tmp_bill_array_sum = $G_SHOP->DBCA->stmt_query($sql_string);
        if($tmp_bill_array_sum)
        {
            foreach($tmp_bill_array_sum as $sum)
            {
                $bill_array_sum[$sum->send_date] = $sum->bill_sum;
            }

        }


        if( in_array($bill['send_date'],$send_date_array)) //配送日期开关
        {
            $index = array_search($bill['send_date'],$send_date_array);
            if($send_date_array_sw[$index]==0)
            {
                return array('code'=>'444','message'=>'该配送日期已达上限，请重新选择');
            }

            if($send_date_bill_limit_array[$index]>0)
            {
                if( isset($bill_array_sum[$bill['send_date']]) && $bill_array_sum[$bill['send_date']] >= $send_date_bill_limit_array[$index])
                {
                    return array('code'=>'444','message'=>'该配送日期已达上限，请重新选择');
                }
            }
            else
            {
                return array('code'=>'444','message'=>'该配送日期已达上限，请重新选择');
            }
        }
        else
        {
            return array('code'=>'404','message'=>'配送日期不正确，请重新选择');
        }

        /**
         * =====================
         * 省市区查询
         * =====================
         */
        $args_array = array(
            'id' => $bill['deliver_provinceid'],
            'region_level' => 1
        );
        $province_array = $sysRegion->getAreaManageList( $args_array );
        $args_array = array(
            'id' => $bill['deliver_cityid'],
            'region_level' => 2
        );
        $city_array = $sysRegion->getAreaManageList( $args_array );
        $args_array = array(
            'id' => $bill['country'],
            'region_level' => 3
        );
        $county_array = $sysRegion->getAreaManageList( $args_array );


        /**
         * ================
         * 收货地址
         * ================
         */
        $args_array = array(
            'pcustID' => $customer_array['pcustID'],
            'creator' => $bill['custID'],
            'custName' => $bill['deliver_name'],
            'provinceid' => $province_array[0]['id'],
            'cityid' => $city_array[0]['id'],
            'countyid' => $county_array[0]['id'],
            'address' => $bill['deliver_address'],
            'mobile' => $bill['deliver_mobile'],
            'phone' => ''
        );


        $deliver_array_s = $custDeliver->searchCustDeliver( $args_array );

        if($deliver_array_s)
        {
            $deliver_array = $deliver_array_s[0];
        }
        else
        {
            $result_deliver = $custDeliver->editCustDeliver( $args_array );
            if ($result_deliver['code'] != 200) {
                return $result_deliver;
            }
            else
            {
                $deliver_array = $result_deliver['data'];
            }
        }

        /**
         * ================
         * 发票
         * ================
         */
        if ($bill['invoice_title_type']) {
            $args_array = array(
                'creator' =>$bill['custID'],
                'pcustID' => $customer_array['pcustID'],
                'invoice_type' => $bill['invoice_type'],
                'invoice_title_type' => $bill['invoice_title_type'],
                'invoice_title' => $bill['invoice_title'],
            );
            $result_array = $custInvoice->editCustInvoice( $args_array );
            if ($result_array['code'] == 200) {
                $invoice_array = $result_array['data'];
            }
        }

        /**
         * ================
         * 查询配送站
         * ================
         */
        $areaID = $billCheckout->getMapArea( $deliver_array['longitude'], $deliver_array['latitude'], $city_array[0]['id'], 2);

        if($areaID['areaID'] == 0)
        {
            return array('code'=>404,'message'=>'抱歉,该地址不属于免费配送区域!');
        }
        $areaID = $billCheckout->getMapArea( $deliver_array['longitude'], $deliver_array['latitude'], $city_array[0]['id'], 1);

        //查询地图区域和配送站的映射关系
        $args_array = array(
            'areaID' => $areaID['areaID']
        );
        $distribution_map_area = $sysDistribution->searchDistributionMapArea( $args_array );
        if($distribution_map_area) {
            $distribution_id = $distribution_map_area[0]['distribution_id'];
        }

        if (isset($distribution_id)) {
            //查询配送站
            $args_array = array(
                'distribution_id' => $distribution_id,
                'useFlg' => 1
            );
            $distribution_array = $sysDistribution->search( $args_array );
        }

        /**
         * ================
         * 查询配送方式
         * ================
         */
        $result_array = $billCheckout->getMapArea( $deliver_array['longitude'], $deliver_array['latitude'], $city_array[0]['id'], 2);
        $areaID = $result_array['areaID'];
        if ($areaID == 0) {
            $areaID = $result_array['default_areaID'];
        }

        //查询地图区域下的所有配送区域
        $args_array = array(
            'areaID' => $areaID
        );
        $send_area_array = $sysSend->searchSendArea( $args_array );
        if (!$send_area_array) {
            return $send_area_array;
        }

        //根据配送区域查询配送方式
        $args_array = array(
            'sendTypeID' => $send_area_array[0]['sendTypeID']
        );
        $sendType_array = $sysSend->searchSendType( $args_array );

        if($send_area_array[0]['freight'] > 0)
        {
            return array('code'=>404,'message'=>'抱歉,该地址不属于免费配送区域!');
        }

        $bill_no = generate_seqno('seqno_bill');
        $bill_code = $city_array[0]['alias'] . get_bill_code( 'seqno_bill_code' . $city_array[0]['alias'] );

        /**
         * ================
         * 查询支付方式
         * ================
         */
        $pay_type_array = $sysPayment->searchPayTypeDetail( $bill['payTypeID'] );

        if (!$pay_type_array) {
            return $pay_type_array;
        }

        if ($pay_type_array['type'] == 1 ) {
            if (!isset($bill['payment_method_id']) || !quanli_is_int($bill['payment_method_id'])) {
                return array('code'=>404,'message'=>'支付方式不存在');
            }
            $args_array = array(
                'id' => $bill['payment_method_id']
            );


            $payment_array = $sysPayment->searchPaymentMethod( $args_array );

            if (!$payment_array) {
                returnJsonData('支付方式不存在', 404);
            }
        }

        $bill_totalMoney = 0;//订单总金额,根据商品的标准售价计算出的，不含运费
        $bill_totalPaid = 0;//订单商品实际成交金额,不含运费，不含附加费
        $bill_accessories_money = 0; //订单配件金额
        $bill_subtract_money = 0; //订单立减金额
        $bill_coupon_money = 0; //订单优惠券订单金额
        $bill_card_money = 0; //代金卡抵扣金额
        $bill_paying_agent_money = 0; //代付订单总金额
        $bill_points_money = 0; //订单总积分价格??????
        $bill_balance_money = 0; //余额抵扣金额
        $bill_online_money = 0; //在线支付已付金额
        $deliver_fee = $send_area_array[0]['freight']; //运费
        $deliver_feePaid = $deliver_fee; //实收运费

        $bill_totalAmount = 0;

        //临时数组
        $temp_array = array(
            'pay_id' => array(),
            'pay_name' => array(),
            'goods' => array(),
            'coupon_code' => array(),
            'card_code' => array(),
            'paying_agent_str' => array()
        );

        /**
         * ===================
         * 订单商品
         * ===================
         */
        $bill_goods_array = array();

        $bill_goods_fittings_array = array();

        $tableware_amount = 0;

        $candle_amount = 0;

        foreach($goods_array as &$goods) {

            $args_array = array(
                'product_code' => $goods['sku'],
            );
            $goods_info = $quanliGoods->searchGoodsSaleDetail( $args_array );
            if (!$goods_info) {
                return  array(
                    'code' => 404,
                    'message' => '没有商品' . $goods['sku']
                );
            }

            $bill_goods_obj = new entity('bill_goods');
            $bill_goods_obj->creator = $bill['custID'];
            $bill_goods_obj->bill_no = $bill_no;
            $bill_goods_obj->bill_goods_no = generate_seqno('seqno_bill_goods');
            $bill_goods_obj->goods_goodsID = $goods_info['goodsID'];
            $bill_goods_obj->goods_postID = $goods_info['postID'];
            $bill_goods_obj->product_code = $goods_info['product_code'];
            $bill_goods_obj->goods_name = $goods_info['goodsName'];
            $bill_goods_obj->goods_spec = $goods_info['spec'];
            $bill_goods_obj->goods_amount = 1;
            $bill_goods_obj->goods_marketPrice = $goods_info['marketPrice'];
            $bill_goods_obj->goods_storePrice = $goods_info['salePrice'];
            $bill_goods_obj->goods_purchasePrice = $goods_info['salePrice'];
            $bill_goods_obj->goods_pointsPrice = 0;
            $bill_goods_obj->goods_points = 0;
            $bill_goods_obj->goods_weight = 0;
            $bill_goods_obj->goods_from = 1;
            $bill_goods_obj->goods_groupID = 0;
            $bill_goods_obj->goods_remark = isset($goods['goods_remark']) ? $goods['goods_remark'] : null;
            $bill_goods_obj->birthday_card = isset($goods['birthday_card']) ? $goods['birthday_card'] : null;
            $bill_goods_obj->segmentation = isset($goods['segmentation']) ? $goods['segmentation'] : 0;
            $bill_goods_array[] = $bill_goods_obj;
            $bill_totalAmount++;
            $bill_totalMoney += $bill_goods_obj->goods_storePrice;
            $bill_totalPaid += $bill_goods_obj->goods_purchasePrice;
            $temp_array['goods'][] = $goods_info['goodsName'];

        }

        //订单金额
        $bill_money = $bill_totalPaid + $bill_accessories_money + $deliver_feePaid + $bill_paying_agent_money;

        //订单应收金额
        $bill_receivable_money = $bill_money - $bill_subtract_money - $bill_coupon_money - $bill_card_money - $bill_balance_money - $bill_points_money - $bill_online_money;


        $bill_pay_array = array();


        //保存订单支付信息
        $pay_status = 0;
        if ($bill_receivable_money >= 0) {

            if ($bill_receivable_money == 0) {
                $pay_status = 1;
            }

            $bill_pay_obj = new entity('bill_pay');
            $bill_pay_obj->creator = $bill['custID'];
            $bill_pay_obj->bill_no = $bill_no;
            $bill_pay_obj->payTypeID = $pay_type_array['payTypeID'];
            $bill_pay_obj->payTypeName = $pay_type_array['payTypeName'];
            $bill_pay_obj->type = $pay_type_array['type'];
            $bill_pay_obj->pay_amount = $bill_receivable_money;
            if ($pay_type_array['type'] == 1) {
                $bill_pay_obj->deduct_amount = 0;
                $bill_pay_obj->payment_method_id = $payment_array[0]['id'];

                $bill_pay_obj->payment_method_name = $payment_array[0]['name'];
                $bill_pay_obj->payment_method_type = $payment_array[0]['type'];


            } else {
                $bill_pay_obj->deduct_amount = 0;
            }

            $bill_pay_array[] = $bill_pay_obj;

            $temp_array['pay_id'][] = $pay_type_array['payTypeID'];
            $temp_array['pay_name'][] = $pay_type_array['payTypeName'];

        }

        $bill_master = new entity('bill_master');
        $bill_master->creator = $bill['custID'];
        if (!empty($bill['createTime'])) {
            $bill_master->createTime = $bill['createTime'];
        }

        if($pay_type_array['type'] == 1 && isset($payment_array))
        {
            $bill_master->payment_method_id =  $payment_array[0]['id'];
            $bill_master->payment_method_name = $payment_array[0]['name'];

        }
        $bill_master->bill_no = $bill_no;
        $bill_master->bill_code = $bill_code;
        $bill_master->pcustID = $customer_array['pcustID'];
        $bill_master->custID = $customer_array['custID'];
        $bill_master->bill_status = 0 ;//状态已确认
        $bill_master->billPromotion = $bill['billPromotion'];

        $bill_master->bill_totalMoney = $bill_totalMoney;
        $bill_master->bill_totalPoints = round($bill_money / 4);
        $bill_master->bill_accessories_money = $bill_accessories_money;
        $bill_master->bill_paying_agent_money = $bill_paying_agent_money;
        $bill_master->bill_subtract_money = $bill_subtract_money;
        $bill_master->bill_coupon_money = $bill_coupon_money;
        $bill_master->bill_pointsPrice = 0;
        $bill_master->bill_money = $bill_money;
        $bill_master->bill_totalPaid = $bill_totalPaid;
        $bill_master->bill_card_money = $bill_card_money;
        $bill_master->bill_balance_money = $bill_balance_money;
        $bill_master->bill_points_money = $bill_points_money;
        $bill_master->bill_online_money = $bill_online_money;
        $bill_master->bill_receivable_money = $bill_receivable_money;
        $bill_master->bill_received_money = $bill_money - $bill_receivable_money;

        $bill_master->deliverid = $deliver_array['deliverID'];
        $bill_master->deliver_name = encryptD($deliver_array['custName']);
        $bill_master->deliver_province = $deliver_array['provinceName'];
        $bill_master->deliver_provinceid = $deliver_array['provinceid'];
        $bill_master->deliver_city = $deliver_array['cityName'];
        $bill_master->deliver_cityid = $deliver_array['cityid'];
        $bill_master->deliver_county = $deliver_array['countyName'];
        $bill_master->deliver_countyid = $deliver_array['countyid'];
        $bill_master->deliver_address = encryptD($deliver_array['address']);
        $bill_master->deliver_mobile = encryptD($deliver_array['mobile']);
        $bill_master->deliver_phone = encryptD($deliver_array['phone']);
        $bill_master->bill_other_address_pay = $deliver_array['precise'];//收货地址精确度

        $bill_master->send_date = $bill['send_date'];
        $bill_master->send_start_time = $bill['send_start_time'];
        $bill_master->send_end_time = $bill['send_end_time'];
        if (isset($distribution_array)) {
            $bill_master->distribution_id = $distribution_array[0]['distribution_id'];
            $bill_master->distribution_name = $distribution_array[0]['distribution_name'];
        }
        if (isset($distribution_technicia_array)) {
            $bill_master->distribution_technician_id = $distribution_technicia_array[0]['distribution_technician_id'];
            $bill_master->distribution_technicia = $distribution_technicia_array[0]['distribution_technicia'];
        }
        $bill_master->sendTypeID = $sendType_array[0]['sendTypeID'];
        $bill_master->sendTypeName = $sendType_array[0]['sendTypeName'];
        $bill_master->send_region_id = $send_area_array[0]['send_region_id'];
        $bill_master->send_region_name = $send_area_array[0]['send_region_name'];
        $bill_master->pay_type = $pay_type_array['type'];
        $bill_master->payTypeID = $pay_type_array['payTypeID'];
        $bill_master->payTypeName = $pay_type_array['payTypeName'];
        $bill_master->pay_status = $pay_status;
        $bill_master->remark = $bill['remark'];
        $bill_master->billPlatform = 1;
        $bill_master->billChannel = $bill['billChannel'];
        $bill_master->billType = $bill['billType'];
        if ($bill['invoice_title_type']) {
            $bill_master->invoice = 1;
            $bill_master->invoiceID = $invoice_array['invoiceID'];
        } else {
            $bill_master->invoice = 0;
            $bill_master->invoiceID = 0;
        }
        $bill_master->invoice_type = 1;
        $bill_master->invoice_title_type = $bill['invoice_title_type'];
        $bill_master->invoice_title = $bill['invoice_title'];
        $bill_master->invoice_content = $bill['invoice_content'];
        $bill_master->invoice_amount = $bill['invoice_amount'];
        $bill_master->invoice_number = $bill['invoice_number'];
        $bill_master->is_the_invoice = $bill['is_the_invoice'];
        $bill_master->is_urgent = $bill['is_urgent'];
        $bill_master->external_bill_no = $bill['external_bill_no'];
        $bill_master->bill_totalAmount = $bill_totalAmount;
        $bill_master->deliver_fee = $deliver_fee;
        $bill_master->deliver_feePaid = $deliver_feePaid;
        $bill_master->tableware_amount = $tableware_amount;
        $bill_master->candle_amount = $candle_amount;
        $bill_master->pay_name_str = implode(',', $temp_array['pay_name']);
        $bill_master->pay_id_str = implode(',', $temp_array['pay_id']);
        $bill_master->goods_name_str = implode(',', $temp_array['goods']);
        $bill_master->coupon_code = implode(',', $temp_array['coupon_code']);
        $bill_master->card_code = implode(',', $temp_array['card_code']);
        $bill_master->paying_agent_str = implode(',', $temp_array['paying_agent_str']);
        //add by allen.qiang 20150428 MK-FUN-1014-MCAKE-订单查询优化方案 start
        //保存反转的订单号，用于查询订单时，部分订单号HIT索引
        $bill_master->bill_code_reverse = strrev($bill_master->bill_code);
        //add by allen.qiang 20150428 MK-FUN-1014-MCAKE-订单查询优化方案 end

        /**
         * 内部留言
         */
        $bill_remark_array = array();
        if (isset($bill['remark']) && !empty($bill['remark'])) {

            foreach($bill['remark'] as &$remark) {
                $bill_remark_obj = new entity('bill_remark');
                $bill_remark_obj->creator = $bill['custID'];
                $bill_remark_obj->createTime = $remark['createTime'];
                $bill_remark_obj->bill_no = $bill_no;
                $bill_remark_obj->remark = $remark['remark'];
                $bill_remark_array[] = $bill_remark_obj;
            }

        }

        try {

            $G_SHOP->DBCA->beginTransaction();

            //保存订单主表
            $G_SHOP->DBCA->save($bill_master);

            //保存订单商品
            foreach($bill_goods_array as &$goods_obj) {

                if ($bill_master->bill_status > 0) {

                    $bill_goods_product = new entity('bill_goods_product');
                    $bill_goods_product->timeStamp = $G_SHOP->sys_datetime;
                    $bill_goods_product->creator = $bill['custID'];
                    $bill_goods_product->createTime = $G_SHOP->sys_datetime;
                    $bill_goods_product->bill_no = $goods_obj->bill_no;
                    $bill_goods_product->bill_goods_no = $goods_obj->bill_goods_no;
                    $bill_goods_product->bill_code = $bill_master->bill_code;
                    $bill_goods_product->cityID = $bill_master->deliver_cityid;
                    $bill_goods_product->cityName = $bill_master->deliver_city;
                    $bill_goods_product->billType = $bill_master->billType;
                    $bill_goods_product->send_date = $bill_master->send_date;
                    $bill_goods_product->send_start_time = $bill_master->send_start_time;
                    $bill_goods_product->send_end_time = $bill_master->send_end_time;
                    $bill_goods_product->distribution_id = $bill_master->distribution_id;
                    $bill_goods_product->distribution_name = $bill_master->distribution_name;
                    $bill_goods_product->is_urgent = $bill_master->is_urgent;
                    $bill_goods_product->goods_postID = $goods_obj->goods_postID;
                    $bill_goods_product->product_code = $goods_obj->product_code;
                    $bill_goods_product->goods_name = $goods_obj->goods_name;
                    $bill_goods_product->goods_spec = $goods_obj->goods_spec;
                    $bill_goods_product->goods_amount = $goods_obj->goods_amount;
                    $bill_goods_product->tableware_amount = $goods_obj->tableware_amount;
                    $bill_goods_product->extra_tableware_amount = $goods_obj->extra_tableware_amount;
                    $bill_goods_product->candle_amount = $goods_obj->candle_amount;
                    $bill_goods_product->extra_candle_amount = $goods_obj->extra_candle_amount;
                    $bill_goods_product->birthday_card = $goods_obj->birthday_card;
                    $bill_goods_product->segmentation = $goods_obj->segmentation;
                    $bill_goods_product->goods_remark = $goods_obj->goods_remark;
                    $G_SHOP->DBCA->save($bill_goods_product);

                }

                $G_SHOP->DBCA->save($goods_obj);

            }

            foreach($bill_goods_fittings_array as &$fit_obj) {
                $G_SHOP->DBCA->save($fit_obj);
            }

            //保存订单支付
            foreach($bill_pay_array as &$pay_obj) {
                $G_SHOP->DBCA->save($pay_obj);
            }

            if (!empty($bill_remark_array)) {
                foreach($bill_remark_array as &$remark_obj) {
                    $G_SHOP->DBCA->save($remark_obj);
                }
            }

            /**
             * ==========================
             * 渠道订单
             * ==========================
             */
            if($bill_master->bill_receivable_money==0){
                $tracker_code = $G_SHOP->get_cookie_info('__etrack_tracker_code');
                $key1 = $G_SHOP->get_cookie_info('__etrack_key1');
                $key2 = $G_SHOP->get_cookie_info('__etrack_key2');
                $key3 = $G_SHOP->get_cookie_info('__etrack_key3');
                $referrer = $G_SHOP->get_cookie_info('__etrack_referrer');
                $referrer_time = $G_SHOP->get_cookie_info('__etrack_referrer_time');
                if ($tracker_code || $key1 || $key2 || $key3 || $referrer) {

                    $tracker = $G_SHOP->get_cookie_info('__etrack');
                    $tracker_array = explode('|', $tracker);
                    $etrack_switch = $G_SHOP->get_cookie_info('__etrack_switch');

                    $bill_channel = new entity('bill_channel');
                    $bill_channel->bill_no = $bill_master->bill_no;
                    if (!$G_SHOP->DBCA->fetch($bill_channel)) {
                        $bill_channel->creator =  $bill_master->creator;
                        $bill_channel->bill_no = $bill_master->bill_no;
                        $bill_channel->bill_code = $bill_master->bill_code;
                        $bill_channel->source_url = $referrer;
                        $bill_channel->source_time = $referrer_time;
                        $bill_channel->key1 = $key1;
                        $bill_channel->key2 = $key2;
                        $bill_channel->key3 = $key3;
                        $bill_channel->tracker_code = $tracker_code;
                        $bill_channel->session_id = $tracker_array[0];
                        $bill_channel->switch_id = $etrack_switch;
                        $bill_channel->ip = get_ip();
                        $bill_channel->source_channel = 'wap';
                        $G_SHOP->DBCA->save( $bill_channel );
                    }
                }
            }
            /**
             * ==========================
             * 渠道订单
             * ==========================
             */

            $G_SHOP->DBCA->commit();

            return array(
                'code' => 200,
                'message' => 'ok',
                'bill_no' => $bill_no,
                'bill_code' => $bill_code
            );
        } catch (Exception $e) {

            $G_SHOP->DBCA->rollBack();

            if ($e->getCode() > 0) {
                return array(
                    'code' => $e->getCode(),
                    'message' => $e->getMessage()
                );

            } else {
                error_log($e->getMessage());
                return array(
                    'code' => 500,
                    'message' => '系统错误'
                );
            }

        }

    }

    /**
     * 判断会员是否购买“拿破仑mini”
     * @$arg_array 参数对象
     * @return $result_array
     * @author  2015-03-10 allen.qiang <allen.qiang@fistforward.com>
     */
    public function isCompetenceBD(&$arg_array,$config_code){
        global $G_SHOP;

        $result_array = array(
            'code' => 200,
            'message' => 'ok'
        );

        //实例化配置类
        $activity_config = new activityConfig($config_code);
        $config_array = $activity_config->config;
        //sql字符串
        $sql = ' ';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //会员名
        if (isset($arg_array['custID']) && is_numeric($arg_array['custID'])) {
            $sql .= ' AND custID = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['custID']);
        }

        //会员ID
        if (isset($arg_array['pcustID']) && !empty($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['pcustID'];
        }

        //判断会员是否已购买过“0元拿破仑mini”---start

        $sql_master="SELECT COUNT(1) AS item_count FROM bill_master WHERE billPromotion =476 ". $sql ." AND bill_status<>10 AND bill_no IN (SELECT bill_no FROM bill_goods WHERE bill_no = bill_master.bill_no AND product_code = 'X0302' )";

        $temp_iteml_master = &$G_SHOP->DBCA->stmt_query($sql_master,$params_type,$params_array);
        if($temp_iteml_master && $temp_iteml_master[0]->item_count>0){
            $result_array['code'] = 405;
            $result_array['message'] = '本号码已购买过9.9元拿破仑mini蛋糕，无法参与此活动！';
        }else{
            $sql_master2="SELECT COUNT(1) AS item_count FROM bill_master WHERE billPromotion =477 ". $sql ." AND bill_status<>10 AND bill_no IN (SELECT bill_no FROM bill_goods WHERE bill_no = bill_master.bill_no AND product_code = 'X0301' )";
            $temp_iteml_master2 = &$G_SHOP->DBCA->stmt_query($sql_master2,$params_type,$params_array);
            if($temp_iteml_master2 && $temp_iteml_master2[0]->item_count>0){
                $result_array['code'] = 407;
                $result_array['message'] = '本号码已购买过1元拿破仑mini蛋糕，无法参与此活动！';
            }else{
                $params_type .= 's';
                $params_array[] = $config_array['sku'];
                $sql_bill_master="SELECT COUNT(1) AS item_count FROM bill_master WHERE billPromotion =".$config_array["billPromotion"]. $sql ." AND bill_status<>10 AND bill_no IN (SELECT bill_no FROM bill_goods WHERE bill_no = bill_master.bill_no AND product_code = ? )";
                $temp_item_bill_master = &$G_SHOP->DBCA->stmt_query($sql_bill_master,$params_type,$params_array);
                if($temp_item_bill_master){
                    $item_count = $temp_item_bill_master[0]->item_count;
                    if ($item_count> 0) { //会员已购买过“0元拿破仑mini”
                        $result_array['code'] = 402;
                        $result_array['message'] = '对不起，本号码已购买过本次拿破仑mini蛋糕';
                    }
                }
            }
        }
        //判断活动蛋糕数量是否超额
        if($result_array['code']==200){

            $bill_master="SELECT COUNT(1) AS item_count FROM bill_master WHERE billPromotion =".$config_array["billPromotion"] ." AND bill_status<>10 AND bill_no IN (SELECT bill_no FROM bill_goods WHERE bill_no = bill_master.bill_no AND product_code = ? )";
            $item_bill_master = &$G_SHOP->DBCA->stmt_query($bill_master,'s',$config_array['sku']);
            if($item_bill_master &&  $item_bill_master[0]->item_count>=$config_array['cake_num']){
                $result_array['code'] = 409;
                $result_array['message'] = '非常抱歉！您来晚了！本次拿破仑mini限量1000份，请下次再来参与吧~';
            }
        }

        //判断会员是否已购买过“0元拿破仑mini”---end
        return $result_array;
    }

} 